package com.sc.demo1.core.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.sc.admin.api.ImportExportService;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.dto.WebResponseDto;
import com.sc.common.entity.admin.importexport.SysImportExport;
import com.sc.common.entity.admin.importexport.SysImportExportSearch;
import com.sc.common.exception.BusinessException;
import com.sc.common.service.ImportService;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.SpringContextHolder;
import com.sc.generatorcode.utils.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * @author ：wust
 * @date ：Created in 2019/7/19 15:21
 * @description：
 * @version:
 */
@Component
@RabbitListener(
        containerFactory = "singleListenerContainer",
        bindings = @QueueBinding(
                value = @Queue(
                        value = "${spring.rabbitmq.importexcel.queue.name}",
                        durable = "${spring.rabbitmq.importexcel.queue.durable}"
                ),
                exchange = @Exchange(
                        value = "${spring.rabbitmq.importexcel.exchange.name}",
                        durable = "${spring.rabbitmq.importexcel.exchange.durable}",
                        type = "${spring.rabbitmq.importexcel.exchange.type}",
                        ignoreDeclarationExceptions = "${spring.rabbitmq.importexcel.exchange.ignoreDeclarationExceptions}"
                ),
                key = "${spring.rabbitmq.importexcel.routing-key}"
        )
)
public class Consumer4ImportExcelQueue {
    static Logger logger = LogManager.getLogger(Consumer4ImportExcelQueue.class);

     @Autowired
  private ImportExportService importExportService;

    @Autowired
    private Environment environment;

    @RabbitHandler
    public void process(JSONObject jsonObject) {
        WebResponseDto responseDto = new WebResponseDto();

        String applicationName = jsonObject.getString("spring.application.name");
        String applicationName1 = environment.getProperty("spring.application.name");

        if(MyStringUtils.isBlank(applicationName)){
            throw new BusinessException("请指定目标服务名");
        }


        if(!applicationName.equals(applicationName1)){
            return;
        }

        DefaultBusinessContext ctx = jsonObject.getObject("ctx",DefaultBusinessContext.class);
        DefaultBusinessContext.copyToCurrentThread(ctx);
        try {
            this.before(jsonObject);
            responseDto = this.doImport(jsonObject);
        }catch (Exception e){
            responseDto.setCode("A100504");
            if(MyStringUtils.isNotBlank(e.getMessage())){
                int length = e.getMessage().length() >= 500 ? 500 : e.getMessage().length();
                responseDto.setMessage(e.getMessage().substring(0,length));
            }else{
                int length = e.toString().length() >= 500 ? 500 : e.toString().length();
                responseDto.setMessage("导入失败:" + e.toString().substring(0,length));
            }
        }finally {
            this.after(jsonObject,responseDto);
        }
    }

    /**
     * 导入之前，记录初始状态和开始时间
     */
    private void before(JSONObject jsonObject){
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        SysImportExport sysImportExport = jsonObject.getObject("sysImportExport", SysImportExport.class);
        importExportService.insert(JSONObject.toJSONString(ctx),sysImportExport);
    }

    /**
     * 执行导入
     */
    private WebResponseDto doImport(JSONObject jsonObject){
        WebResponseDto responseDto = new WebResponseDto();
        String xmlName = jsonObject.getString("xmlName");
        String beanName = StringUtil.columnName2PropertyName(xmlName).concat("ImportServiceImpl");
        ImportService importService = SpringContextHolder.getBean(beanName);
        if(importService != null){
            return importService.importByExcel(jsonObject);
        }else{
            responseDto.setFlag(WebResponseDto.INFO_ERROR);
            responseDto.setMessage("未知的bean["+beanName+"]");
        }
        return responseDto;
    }

    /**
     * 导入后记录导入结果和结束时间
     */
    private void after(JSONObject jsonObject, WebResponseDto importResponseDto){
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        SysImportExport sysImportExport = jsonObject.getObject("sysImportExport", SysImportExport.class);
        SysImportExportSearch importExportSearch = new SysImportExportSearch();
        importExportSearch.setBatchNo(sysImportExport.getBatchNo());
        WebResponseDto responseDto = importExportService.selectOne(JSONObject.toJSONString(ctx),importExportSearch);
        if(!responseDto.isSuccess()){
            throw new BusinessException(responseDto.getMessage());
        }

        SysImportExport importExport = JSONObject.parseObject(JSONObject.toJSONString(responseDto.getObj()),SysImportExport.class);
        if(importExport != null){
            importExport.setStatus(importResponseDto.getCode());
            importExport.setMsg(importResponseDto.getMessage());
            importExport.setEndTime(new Date());
            importExport.setModifyTime(new Date());
            importExportService.updateByPrimaryKeySelective(JSONObject.toJSONString(ctx),importExport);
        }
    }
}
